<template>
	<view class="page" :style="{color: fontColor}">
		<view class="title" v-if="!isStart">
			距离开始：
		</view>
		<view class="title" v-else>
			距离结束：
		</view>
		<view class="days">
			{{time.day || '00'}}天
		</view>
		<view class="hour">
			{{time.hour || '00'}}时
		</view>
		<view class="minutes">
			{{time.min || '00'}}分
		</view>
		<view class="security">
			{{time.sec || '00'}}秒
		</view>
	</view>
</template>
 
<script>
	export default {
		data () {
			return {
				time: {},
				isStart: false,
			}
		},
		props: {
			start_time: String,
			end_time: String,
			fontColor: String
		},
		mounted() {
			this.countDown()
		},
		methods: {
			timeFormat(param) {
				return param < 10 ? '0' + param : param;
			},
			countDown () {
				var interval = setInterval(() => {
					// 当前时间
					let nowTime = new Date().getTime();
					let endTime = new Date((this.end_time.replace(/-/g,'/'))).getTime();
					let startTime = new Date((this.start_time.replace(/-/g,'/'))).getTime();
					// 已开始
					if (startTime - nowTime <= 0) {
                        if (endTime - nowTime <= 0) {
						   // 计时结束
						    clearInterval(interval)
					    } else {
                            this.isStart = true;
						    let time = (endTime - nowTime) / 1000;
						    let day = parseInt(time / (60*60*24));
						    let hour = parseInt(time % (60*60*24) / 3600);
						    let min = parseInt(time % (60*60*24) % 3600 / 60);
						    let sec = parseInt(time % (60*60*24) % 3600 %60);
						    this.time = {
							    day: this.timeFormat(day),
							    hour: this.timeFormat(hour),
							    min: this.timeFormat(min),
							    sec: this.timeFormat(sec)
						    }
                        }
					} else if (startTime - nowTime > 0) {  // 即将开始
						this.isStart = false
						let time = (startTime - nowTime) / 1000;
						let day = parseInt(time / (60*60*24));
						let hour = parseInt(time % (60*60*24) / 3600);
						let min = parseInt(time % (60*60*24) % 3600 / 60);
						let sec = parseInt(time % (60*60*24) % 3600 %60);
						this.time = {
							day: this.timeFormat(day),
							hour: this.timeFormat(hour),
							min: this.timeFormat(min),
							sec: this.timeFormat(sec)
						}
					}
				}, 1000)
			}
		}
	}
</script>
 
<style lang="scss" scoped>
	.page {
		width: 100%;
		font-size: 24upx;
		display: flex;
		align-items: center;
		.days,.title {
			margin-right: 10upx;
		}
	}
</style>